package com.shchuangzhi.smartguard.fragment;


import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import com.elvishew.xlog.XLog;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;
import com.shchuangzhi.smartguard.R;
import com.shchuangzhi.smartguard.SharedPref;
import com.shchuangzhi.smartguard.core.Consts;
import com.shchuangzhi.smartguard.core.DBHelper;
import com.shchuangzhi.smartguard.core.ImageUploader;
import com.shchuangzhi.smartguard.core.Job;
import com.shchuangzhi.smartguard.core.JobManager;
import com.shchuangzhi.smartguard.core.Machine;
import com.shchuangzhi.smartguard.core.Notify;
import com.shchuangzhi.smartguard.core.NotifyMessage;
import com.shchuangzhi.smartguard.core.NotifyPrinter;
import com.shchuangzhi.smartguard.core.command.Command;
import com.shchuangzhi.smartguard.core.receiver.ReceiverGridViewAdapter;
import com.shchuangzhi.smartguard.core.receiver.ReceiverInOutData;

/**
 * A simple {@link Fragment} subclass.
 */
public class Receiver extends Fragment implements FragmentNamed {
    private GridView gridView;
    private ReceiverGridViewAdapter gridAdapter;

    private Handler onListChangedHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            gridAdapter.reload();
        }
    };

    private Handler getCredentialHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Uri uri = ImageUploader.getInstance().getOutputMediaFileUri();
            if (uri != null) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
            }
        }
    };

    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;

    public Receiver() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_receiver, container, false);
        gridView = (GridView)view.findViewById(R.id.receiver_gridview);
        gridAdapter = new ReceiverGridViewAdapter(
                this.getActivity(), ReceiverInOutData.getInstance().getDataViewList());
        gridView.setAdapter(gridAdapter);
        gridView.setOnScrollListener(new PauseOnScrollListener(ImageLoader.getInstance(), true ,true));

        gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                ReceiverInOutData.InOutDataView item = gridAdapter.getItem(position);
                if (item.uploadEnabled()) {
                    ImageUploader uploader = ImageUploader.getInstance();
                    uploader.bindData(item);
                    uploader.execute(ImageUploader.AsyncTaskType.GET_TOKEN);
                }
                return true;
            }
        });

        Job dataSyncJob = JobManager.get(Consts.JOB_RECEIVER_DATA_SYNC);
        Command command = (Command)dataSyncJob.getData();
        command.setNotifier(dataSyncJob);
        dataSyncJob.addNotify(Consts.NOTIFY_RECEIVER_DATA_VIEW_CHANGEED, new Notify() {
            @Override
            public void notify(NotifyMessage message) {
                onListChangedHandler.sendMessage(
                        onListChangedHandler.obtainMessage(Consts.NOTIFY_RECEIVER_DATA_VIEW_CHANGEED, message));
            }
        });

        NotifyPrinter.getInstance().addNotify(Consts.NOTIFY_IMAGE_CREDENTIAL_GET, new Notify() {
            @Override
            public void notify(NotifyMessage message) {
                getCredentialHandler.sendMessage(
                        getCredentialHandler.obtainMessage(Consts.NOTIFY_IMAGE_CREDENTIAL_GET, message));
            }
        });

        ImageUploader.getInstance().init(this.getActivity());

        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                ImageUploader.getInstance().execute(ImageUploader.AsyncTaskType.UPLOAD);
            } else if (resultCode == Activity.RESULT_CANCELED) {
                NotifyPrinter.getInstance().notify(NotifyMessage.info(Consts.UPLOAD_IMAGE_CANCEL));
            } else {
                NotifyPrinter.getInstance().notify(NotifyMessage.info(Consts.UPLOAD_IMAGE_FAIL));
            }
        }
    }

    @Override
    public String Name() {
        return Consts.RECEIVER_FRAGMENT_NAME;
    }

    @Override
    public Fragment Fragment() {
        return this;
    }
}
